#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_container = new QX11EmbedContainer(this);
    m_process = new QProcess(m_container);
    m_timer = new QTimer();
    m_file = new QFile();
}

bool MainWindow::startRecording() {
    if (!m_file->open(stdout, QIODevice::WriteOnly)) {
        qDebug() << "Could not open stdout";
        return false;
    }
    if (m_imageFormat.isNull() || m_resolution.isNull() || m_keylayout.isNull() || m_serverName.isNull()) {
        qDebug() << "imageformat, resolution, keylayout or servername is not set.";
        return false;
    }
    m_imageWriter = new QImageWriter(m_file,m_imageFormat.toAscii());

    connect(m_timer,SIGNAL(timeout()),this,SLOT(capture()));

    this->setCentralWidget(m_container);
    m_container->show();

    QStringList arguments;
    arguments << "-g" << QString("%0").arg(m_resolution);
    arguments << "-k" << QString("%1").arg(m_keylayout);
    arguments << "-D";
    arguments << "-X" << QString::number(m_container->winId());
    arguments << QString("%0").arg(m_serverName);
    qDebug() << "Launching rdesktop with " << arguments << "as arguments";
    m_process->start("rdesktop", arguments);
    QDir dir;
    if (!dir.exists("capture")) {
        dir.mkdir("capture");
    }
    m_timer->setInterval(100);
    m_timer->start();
    return true;
}

MainWindow::~MainWindow()
{
    m_file->close();
    m_file->deleteLater();
    m_process->close();
    m_process->deleteLater();
    m_container->close();
    m_container->deleteLater();
    m_timer->stop();
    m_timer->deleteLater();
    delete ui;
}


void MainWindow::capture() {
    if (m_process->state()!=QProcess::NotRunning){
        QImage snap = QPixmap::grabWindow(m_container->clientWinId()).toImage();
        m_imageWriter->write(snap);
    } else {
        qWarning() << "Error:" << m_process->errorString();
        this->close();
    }
}
